import { asyncRouterMap, constantRouterMap } from "@/router";
const _import = require("../../router/_import_" + process.env.NODE_ENV);
import Layout from "../../views/layout/Layout";
import TestLayout from "../../views/layout/TestLayout";
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(
      role => String(route.meta.role).indexOf(String(role)) >= 0
    );
  } else {
    return false;
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles);
      }
      return true;
    }
    return false;
  });
  return accessedRouters;
}

const permission = {
  state: {
    routers: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { userData } = data;
        var newArr = [
          {
            path: "/",
            component: Layout,
            redirect:
              userData.permissionsInfo[0].showUrl +
              "/" +
              userData.permissionsInfo[0].pageList[0].pageIdentification,
            name: "首页",
            hidden: true
          }
        ];
        var newObj = {};
        var childObj = {};
        userData.permissionsInfo.forEach((item, index) => {
          if (userData.pageTemplate === "Layout") {
            newObj = {
              path: item.showUrl,
              component: Layout,
              name: item.modularName,
              icon: "zonghe",
              children: []
            };
          } else {
            newObj = {
              path: item.showUrl,
              component: TestLayout,
              name: item.modularName,
              icon: "zonghe",
              children: []
            };
          }
          item.pageList.forEach(element => {
            childObj = {
              path: element.pageIdentification,
              icon: "round",
              component: _import(
                // item.actualPath + "/" + element.pageIdentification
                element.pageRealPath
              ),
              name: element.pageName
            };
            newObj.children.push(childObj);
          });
          newArr.push(newObj);
        });
        commit("SET_ROUTERS", newArr);
        // let accessedRouters
        // accessedRouters = asyncRouterMap
        // commit("SET_ROUTERS", accessedRouters)
        resolve();
      });
    }
  }
};

export default permission;
